package com.ruoyi.financial.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.financial.domain.*;
import com.ruoyi.financial.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.financial.mapper.FEnterMapper;
import com.ruoyi.common.core.text.Convert;

/**
 * 入库管理Service业务层处理
 * 
 * @author xunzhe
 * @date 2024-01-31
 */
@Service
public class FEnterServiceImpl implements IFEnterService 
{
    @Autowired
    private FEnterMapper fEnterMapper;

    @Autowired
    private IFOutboundService fOutboundService;

    @Autowired
    private IFThingService thingService;

    @Autowired
    private IFThingTypeService thingTypeService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private IFEnterXuniService enterXuniService;

    /**
     * 查询入库管理
     * 
     * @param enterId 入库管理主键
     * @return 入库管理
     */
    @Override
    public FEnter selectFEnterByEnterId(Long enterId)
    {
        return fEnterMapper.selectFEnterByEnterId(enterId);
    }

    /**
     * 查询入库管理列表
     * 
     * @param fEnter 入库管理
     * @return 入库管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FEnter> selectFEnterList(FEnter fEnter)
    {
        return fEnterMapper.selectFEnterList(fEnter);
    }

    /**
     * 新增入库管理
     * 
     * @param fEnter 入库管理
     * @return 结果
     */
    @Override
    public int insertFEnter(FEnter fEnter)
    {
        fEnter.setCreateTime(DateUtils.getNowDate());
        if(fEnter.getEnterTime() == null){
            fEnter.setEnterTime(DateUtils.getNowDate());
        }
        return fEnterMapper.insertFEnter(fEnter);
    }

    /**
     * 修改入库管理
     * 
     * @param fEnter 入库管理
     * @return 结果
     */
    @Override
    public int updateFEnter(FEnter fEnter)
    {
        fEnter.setUpdateTime(DateUtils.getNowDate());
        return fEnterMapper.updateFEnter(fEnter);
    }

    /**
     * 批量删除入库管理
     * 
     * @param enterIds 需要删除的入库管理主键
     * @return 结果
     */
    @Override
    public int deleteFEnterByEnterIds(String enterIds)
    {
        return fEnterMapper.deleteFEnterByEnterIds(Convert.toStrArray(enterIds));
    }

    /**
     * 删除入库管理信息
     * 
     * @param enterId 入库管理主键
     * @return 结果
     */
    @Override
    public int deleteFEnterByEnterId(Long enterId)
    {
        return fEnterMapper.deleteFEnterByEnterId(enterId);
    }

    public int selectCountByDate(Map map){
        return fEnterMapper.selectCountByDate(map);
    }

    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FEnter> selectFEnterKucun(FEnter fEnter){
        List<FEnter> list = fEnterMapper.selectFEnterKucun(fEnter);
        FOutbound outbound = new FOutbound();
        outbound.setDeptId(fEnter.getDeptId());
        outbound.setThingName(fEnter.getThingName());
        outbound.setCreateName(fEnter.getCreateName());
        outbound.setMohu(fEnter.getMohu());
        outbound.setThingTypeId(fEnter.getThingTypeId());
        outbound.setParams(fEnter.getParams());
        List<FOutbound> outboundList = fOutboundService.selectFOutboundKucun(outbound);

        for(FEnter enter : list){
            enter.setShuliang(enter.getShuliang().split("\\.")[0]);
            enter.setKucunshuliang(enter.getShuliang());
            b:for(FOutbound fOutbound : outboundList){
                if((enter.getMohu()+"").equals(fOutbound.getMohu()+"")){
                    if(enter.getThingTypeId().longValue() == fOutbound.getThingTypeId().longValue() && enter.getDeptId().longValue() == fOutbound.getDeptId().longValue() && enter.getThingId().longValue() == fOutbound.getThingId().longValue()){
                        int shuliang = Integer.parseInt(enter.getShuliang().split("\\.")[0]) - Integer.parseInt(fOutbound.getShuliang().split("\\.")[0]);
                        enter.setKucunshuliang(shuliang+"");
                        enter.setChushuliang(fOutbound.getShuliang().split("\\.")[0]);
                        enter.setRenjunxiaohao(fOutbound.getPingjunSunhao());
                        break b;
                    }
                }
            }
        }

        return list;
    }

    public int examine(FEnter fEnter)
    {
        return fEnterMapper.updateFEnter(fEnter);
    }

    public String selectAverageDanjia(FEnter fEnter){
        Map map = fEnterMapper.selectAverageDanjia(fEnter);
        String shuliangStr = map.get("shuliang".toUpperCase()).toString();
        if(shuliangStr.equals("0") || map.get("danjia".toUpperCase())==null){
            return "";
        }else{
            double sumdanjia = Double.parseDouble(map.get("danjia".toUpperCase()).toString());
            double shuliang = Double.parseDouble(map.get("shuliang".toUpperCase()).toString());
            double danjia = sumdanjia/shuliang;
            return  String.format("%.1f", danjia);
        }
    }

    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FEnter> selectFEnterTongji(FEnter fEnter){
        return fEnterMapper.selectFEnterTongji(fEnter);
    }

    @DataScope(deptAlias = "d", userAlias = "u")
    public List<TongJi> selectFEnterTongjiList(FEnter fEnter){
        List<TongJi> tongJiList = fEnterMapper.selectFEnterTongjiList(fEnter);
        TongJi shengTongji = fEnterMapper.selectFEnterShengTongji(fEnter);
        TongJi hangshu = fEnterMapper.selectShengTongjiRenshu(fEnter);

        FEnterXuni enterXuni = new FEnterXuni();
        enterXuni.setDeptId(fEnter.getDeptId());
        enterXuni.setThingTypeId(fEnter.getThingTypeId());
        enterXuni.setParams(fEnter.getParams());
        List<FEnterXuni> xuniList = enterXuniService.selectTongjiList(enterXuni);

        if(tongJiList.size() > 0 && shengTongji != null && shengTongji.getShengShuliang() != null && !shengTongji.getShengShuliang().equals("0")){
            //省均数量
            if(hangshu !=null && hangshu.getDeptShuliang()!=null && !hangshu.getDeptShuliang().equals("0")){
                double v = Double.parseDouble(shengTongji.getShengShuliang()) / Double.parseDouble(hangshu.getDeptShuliang());
                hangshu.setShengjunShuliang(qiaodiao(String.valueOf(v)));
            }
            //全省机构人均用量
            if(hangshu !=null && hangshu.getTotalPeople()!=null && !hangshu.getTotalPeople().equals("0")){
                double v = Double.parseDouble(shengTongji.getShengShuliang()) / Double.parseDouble(hangshu.getTotalPeople());
                hangshu.setShengrenjunliang(qiaodiao(String.valueOf(v)));
            }
        }

        if(shengTongji != null && shengTongji.getShengjundanjia()!=null && !shengTongji.getShengjundanjia().equals("0")){
            shengTongji.setShengjundanjia(qiaodiao(shengTongji.getShengjundanjia()));
        }

        if(shengTongji != null && shengTongji.getShengZonge()!=null && !shengTongji.getShengZonge().equals("0")){
            //全省机构人均支出金额
            if(hangshu !=null && hangshu.getTotalPeople()!=null && !hangshu.getTotalPeople().equals("0")){
                double v = Double.parseDouble(shengTongji.getShengZonge()) / Double.parseDouble(hangshu.getTotalPeople());
                hangshu.setShengrenjunZonge(qiaodiao(String.valueOf(v)));
            }
        }

        for(TongJi tongJi : tongJiList){
            if(tongJi.getMinDanjia()!=null && !tongJi.getMinDanjia().equals("0")){
                tongJi.setMinDanjia(qiaodiao(tongJi.getMinDanjia()));
            }
            if(tongJi.getMaxDanjia()!=null && !tongJi.getMaxDanjia().equals("0")){
                tongJi.setMaxDanjia(qiaodiao(tongJi.getMaxDanjia()));
            }

            //入库数量
            if(tongJi.getSumShuliang()!=null && !tongJi.getSumShuliang().equals("0")){
                tongJi.setSumShuliang(qiaodiao(tongJi.getSumShuliang()));
            }
            tongJi.setShengjunShuliang(hangshu.getShengjunShuliang());

            //平均单价
            if(tongJi.getSumZonge()!=null && !tongJi.getSumZonge().equals("0") && tongJi.getSumShuliang()!=null && !tongJi.getSumShuliang().equals("0")){
                double v = Double.parseDouble(tongJi.getSumZonge()) / Double.parseDouble(tongJi.getSumShuliang());
                tongJi.setPingjundanjia(qiaodiao(String.valueOf(v)));
            }
            tongJi.setShengjundanjia(shengTongji.getShengjundanjia());

            //人均用量
            if(tongJi.getSumShuliang()!=null && !tongJi.getSumShuliang().equals("0") && tongJi.getTotalPeople()!=null && !tongJi.getTotalPeople().equals("0")){
                double v = Double.parseDouble(tongJi.getSumShuliang()) / Double.parseDouble(tongJi.getTotalPeople());
                tongJi.setRenjunliang(qiaodiao(String.valueOf(v)));
            }
            tongJi.setShengrenjunliang(hangshu.getShengrenjunliang());

            //人均支出金额
            if(tongJi.getSumZonge()!=null && !tongJi.getSumZonge().equals("0") && tongJi.getTotalPeople()!=null && !tongJi.getTotalPeople().equals("0")){
                double v = Double.parseDouble(tongJi.getSumZonge()) / Double.parseDouble(tongJi.getTotalPeople());
                tongJi.setRenjunZonge(qiaodiao(String.valueOf(v)));
            }
            tongJi.setShengrenjunZonge(hangshu.getShengrenjunZonge());

            //总支出金额
            if(tongJi.getSumZonge()!=null && !tongJi.getSumZonge().equals("0")){
                tongJi.setSumZonge(qiaodiao(tongJi.getSumZonge()));
            }
            for(int i=0;i<xuniList.size();i++){
                if(tongJi.getDeptId().longValue() == xuniList.get(i).getDeptId().longValue()){
                    String xunizonge = xuniList.get(i).getZonge();
                    if(xunizonge != null && !xunizonge.equals("0")){
                        tongJi.setXunizonge(qiaodiao(xunizonge));
                        xuniList.remove(i);
                        break;
                    }
                }
            }
        }

        return tongJiList;
    }

    public String qiaodiao(String data){
        String str = String.format("%.2f", Float.parseFloat(data));
        str = str.replaceAll("\\.00","");
        return str;
    }

    public String importEnter(List<FEnter> enterList, SysUser sysUser,Long postId){
        if (StringUtils.isNull(enterList) || enterList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        int index = 0;
        for (FEnter fEnter : enterList){
            index++;
            try {
                if(fEnter.getThingName()==null || fEnter.getThingName().equals("")){
                    failureNum++;
                    String msg = "<br/> 物品目录为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
                if(fEnter.getCreateName()==null || fEnter.getCreateName().equals("")){
                    failureNum++;
                    String msg = "<br/> 物品名称为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
                if(fEnter.getFshuliang()==null || fEnter.getFshuliang().equals("")){
                    failureNum++;
                    String msg = "<br/> 数量（发票信息）为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
                if(fEnter.getZonge()==null || fEnter.getZonge().equals("")){
                    failureNum++;
                    String msg = "<br/> 发票金额+税额 为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
                if(fEnter.getGuige()==null || fEnter.getGuige().equals("")){
                    failureNum++;
                    String msg = "<br/> 最小度量物品数量 为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
                if(fEnter.getThingType()==null || fEnter.getThingType().equals("")){
                    failureNum++;
                    String msg = "<br/> 收支项目 为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
                if(fEnter.getDanwei()==null || fEnter.getDanwei().equals("")){
                    failureNum++;
                    String msg = "<br/> 物品单位（发票信息） 为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
//                if(fEnter.getEnterTime()==null || fEnter.getEnterTime().equals("")){
//                    failureNum++;
//                    String msg = "<br/> 入库时间 为空 导入失败";
//                    failureMsg.append(msg);
//                    continue;
//                }
                if(fEnter.getLnvoiceNumber()==null || fEnter.getLnvoiceNumber().equals("")){
                    failureNum++;
                    String msg = "<br/> 发票号 为空 导入失败";
                    failureMsg.append(msg);
                    continue;
                }
//                if(fEnter.getJizhang()==null || fEnter.getJizhang().equals("")){
//                    failureNum++;
//                    String msg = "<br/> 记账凭证 为空 导入失败";
//                    failureMsg.append(msg);
//                    continue;
//                }

                List<FThing> thingList = thingService.selectFThingList(new FThing());
                List<FThingType> thingTypeList = thingTypeService.selectFThingTypeList(new FThingType());
                boolean thingListState = false;
                boolean thingTypeListState = false;
                String jiliangdanwei = "";

                for(FThing thing : thingList){
                    if(fEnter.getThingName().equals(thing.getThingName())){
                        thingListState = true;
                        fEnter.setThingId(thing.getThingId());
                        fEnter.setAncestors(thing.getAncestors());
                        jiliangdanwei = thing.getThingUnit();
                        break;
                    }
                }
                for(FThingType thingType : thingTypeList){
                    if(fEnter.getThingType().equals(thingType.getTypeName())){
                        thingTypeListState = true;
                        fEnter.setThingTypeId(thingType.getTypeId());
                        break;
                    }
                }
                if(thingListState == false){
                    failureNum++;
                    String msg = "<br/>"+index+"行 "+fEnter.getCreateName()+"  导入失败,物品目录不存在";
                    failureMsg.append(msg);
                    continue;
                }
                if(thingTypeListState == false){
                    failureNum++;
                    String msg = "<br/>"+index+"行 "+fEnter.getCreateName()+"  导入失败,收支项目不存在";
                    failureMsg.append(msg);
                    continue;
                }

                List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType("f_jiliangdanwei");
                if(fEnter.getJiliangdanwei()==null || fEnter.getJiliangdanwei().equals("")){
                    fEnter.setJiliangdanwei(jiliangdanwei);
                }
                boolean jiliangdanweiState = false;
                for(SysDictData dictData : sysDictDataList){
                    if(dictData.getDictLabel().equals(fEnter.getJiliangdanwei())){
                        fEnter.setJiliangdanwei(dictData.getDictValue());
                        jiliangdanweiState = true;
                        break;
                    }
                }
                if(jiliangdanweiState == false){
                    fEnter.setJiliangdanwei("0");
                }

                double zonge = Double.parseDouble(fEnter.getZonge());
                double fshuliang = Double.parseDouble(fEnter.getFshuliang());
                double guige = Double.parseDouble(fEnter.getGuige());

                double fdanjia = zonge/fshuliang;
                double shuliang = fshuliang*guige;
                double danjia = zonge/shuliang;

                fEnter.setFdanjia(qiaodiao(fdanjia+""));
                fEnter.setShuliang(qiaodiao(shuliang+""));
                fEnter.setDanjia(qiaodiao(danjia+""));

                fEnter.setCreateBy(sysUser.getLoginName());
                fEnter.setCreateTime(new Date());
                fEnter.setDeptId(sysUser.getDeptId());
                fEnter.setPostId(postId);

                String mohu = "";
                if(fEnter.getPinpai() == null){
                    fEnter.setPinpai("");
                }

                if(fEnter.getPinpai()!=null){
                    mohu = fEnter.getPinpai()+"牌";
                }
                if(fEnter.getXinghao() != null){
                    mohu = mohu + fEnter.getXinghao();
                }

                mohu = mohu + fEnter.getCreateName()+fEnter.getGuige();
                fEnter.setMohu(mohu);
                fEnter.setAverageDanjia("");

                int i = insertFEnter(fEnter);
                if(i > 0){
                    successNum++;
                    successMsg.append("<br/>" + successNum + " " + fEnter.getCreateName() + " 导入成功");
                }

            }catch (Exception e){
                failureNum++;
                String msg = "<br/>"+index+"行 "+fEnter.getCreateName()+"  导入失败";
                failureMsg.append(msg + e.getMessage());
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
